package com.aspire.aimini.controller;

import com.aspire.aimini.service.AiService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * AI服务控制器
 *
 * @author wangguiyou
 * @date 2024-12-19
 */
@Slf4j
@RestController
@RequestMapping("/api/ai")
@RequiredArgsConstructor
@Tag(name = "AI服务", description = "AI相关的API接口")
public class AiController {

    private final AiService aiService;

    /**
     * 图片标签识别
     *
     * @param file   图片文件
     * @param userId 用户ID
     * @return 识别的标签列表
     */
    @PostMapping("/image/tag-recognition")
    @Operation(summary = "图片标签识别", description = "使用AI识别图片中的标签")
    public ResponseEntity<List<String>> recognizeImageTags(
            @Parameter(description = "图片文件") @RequestParam("file") MultipartFile file,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("图片标签识别: userId={}, fileName={}", userId, file.getOriginalFilename());

        List<String> tags = aiService.recognizeImageTags(file, userId);
        return ResponseEntity.ok(tags);
    }

    /**
     * 文案生成
     *
     * @param request 生成请求
     * @param userId  用户ID
     * @return 生成的文案
     */
    @PostMapping("/copywriting/generate")
    @Operation(summary = "文案生成", description = "使用AI生成文案")
    public ResponseEntity<String> generateCopywriting(
            @Valid @RequestBody Map<String, Object> request,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("文案生成: userId={}", userId);

        String prompt = (String) request.get("prompt");
        String contentType = (String) request.get("contentType");
        String style = (String) request.get("style");
        String aiModel = (String) request.get("aiModel");

        String copywriting = aiService.generateCopywriting(prompt, contentType, style, aiModel, userId);
        return ResponseEntity.ok(copywriting);
    }

    /**
     * 相似图片生成
     *
     * @param file    参考图片文件
     * @param request 生成参数
     * @param userId  用户ID
     * @return 生成的图片URL
     */
    @PostMapping("/image/generate-similar")
    @Operation(summary = "相似图片生成", description = "基于参考图片生成相似图片")
    public ResponseEntity<String> generateSimilarImage(
            @Parameter(description = "参考图片文件") @RequestParam("file") MultipartFile file,
            @Valid @RequestBody Map<String, Object> request,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("相似图片生成: userId={}, fileName={}", userId, file.getOriginalFilename());

        String style = (String) request.get("style");
        String aiModel = (String) request.get("aiModel");

        String imageUrl = aiService.generateSimilarImage(file, style, aiModel, userId);
        return ResponseEntity.ok(imageUrl);
    }

    /**
     * 图片内容分析
     *
     * @param file   图片文件
     * @param userId 用户ID
     * @return 分析结果
     */
    @PostMapping("/image/analyze")
    @Operation(summary = "图片内容分析", description = "分析图片内容并生成描述")
    public ResponseEntity<Map<String, Object>> analyzeImageContent(
            @Parameter(description = "图片文件") @RequestParam("file") MultipartFile file,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("图片内容分析: userId={}, fileName={}", userId, file.getOriginalFilename());

        Map<String, Object> analysis = aiService.analyzeImageContent(file, userId);
        return ResponseEntity.ok(analysis);
    }

    /**
     * 图片风格转换
     *
     * @param file    原图片文件
     * @param request 转换参数
     * @param userId  用户ID
     * @return 转换后的图片URL
     */
    @PostMapping("/image/style-transfer")
    @Operation(summary = "图片风格转换", description = "将图片转换为指定风格")
    public ResponseEntity<String> transferImageStyle(
            @Parameter(description = "原图片文件") @RequestParam("file") MultipartFile file,
            @Valid @RequestBody Map<String, Object> request,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("图片风格转换: userId={}, fileName={}", userId, file.getOriginalFilename());

        String targetStyle = (String) request.get("targetStyle");
        String aiModel = (String) request.get("aiModel");

        String imageUrl = aiService.transferImageStyle(file, targetStyle, aiModel, userId);
        return ResponseEntity.ok(imageUrl);
    }

    /**
     * 图片背景移除
     *
     * @param file   图片文件
     * @param userId 用户ID
     * @return 移除背景后的图片URL
     */
    @PostMapping("/image/remove-background")
    @Operation(summary = "图片背景移除", description = "移除图片背景")
    public ResponseEntity<String> removeImageBackground(
            @Parameter(description = "图片文件") @RequestParam("file") MultipartFile file,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("图片背景移除: userId={}, fileName={}", userId, file.getOriginalFilename());

        String imageUrl = aiService.removeImageBackground(file, userId);
        return ResponseEntity.ok(imageUrl);
    }

    /**
     * 图片质量增强
     *
     * @param file    图片文件
     * @param request 增强参数
     * @param userId  用户ID
     * @return 增强后的图片URL
     */
    @PostMapping("/image/enhance")
    @Operation(summary = "图片质量增强", description = "提升图片质量和分辨率")
    public ResponseEntity<String> enhanceImageQuality(
            @Parameter(description = "图片文件") @RequestParam("file") MultipartFile file,
            @Valid @RequestBody Map<String, Object> request,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("图片质量增强: userId={}, fileName={}", userId, file.getOriginalFilename());

        String enhanceType = (String) request.get("enhanceType");
        String aiModel = (String) request.get("aiModel");

        String imageUrl = aiService.enhanceImageQuality(file, enhanceType, aiModel, userId);
        return ResponseEntity.ok(imageUrl);
    }

    /**
     * 文本转图片
     *
     * @param request 生成请求
     * @param userId  用户ID
     * @return 生成的图片URL
     */
    @PostMapping("/image/text-to-image")
    @Operation(summary = "文本转图片", description = "根据文本描述生成图片")
    public ResponseEntity<String> textToImage(
            @Valid @RequestBody Map<String, Object> request,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("文本转图片: userId={}", userId);

        String prompt = (String) request.get("prompt");
        String style = (String) request.get("style");
        String aiModel = (String) request.get("aiModel");

        String imageUrl = aiService.textToImage(prompt, style, aiModel, userId);
        return ResponseEntity.ok(imageUrl);
    }

    /**
     * 图片转文本描述
     *
     * @param file   图片文件
     * @param userId 用户ID
     * @return 图片描述
     */
    @PostMapping("/image/image-to-text")
    @Operation(summary = "图片转文本描述", description = "生成图片的文本描述")
    public ResponseEntity<String> imageToText(
            @Parameter(description = "图片文件") @RequestParam("file") MultipartFile file,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("图片转文本描述: userId={}, fileName={}", userId, file.getOriginalFilename());

        String description = aiService.imageToText(file, userId);
        return ResponseEntity.ok(description);
    }

    /**
     * 获取用户AI配置
     *
     * @param userId 用户ID
     * @return AI配置信息
     */
    @GetMapping("/config")
    @Operation(summary = "获取用户AI配置", description = "获取用户的AI服务配置")
    public ResponseEntity<Map<String, Object>> getUserAiConfig(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("获取用户AI配置: userId={}", userId);

        Map<String, Object> config = aiService.getUserAiConfig(userId);
        return ResponseEntity.ok(config);
    }

    /**
     * 检查AI服务可用性
     *
     * @param serviceType 服务类型
     * @return 可用性状态
     */
    @GetMapping("/availability/{serviceType}")
    @Operation(summary = "检查AI服务可用性", description = "检查指定AI服务的可用性")
    public ResponseEntity<Map<String, Object>> checkAiServiceAvailability(
            @Parameter(description = "服务类型") @PathVariable String serviceType) {
        log.info("检查AI服务可用性: serviceType={}", serviceType);

        boolean available = aiService.checkAiServiceAvailability(serviceType);

        Map<String, Object> result = Map.of(
                "serviceType", serviceType,
                "available", available,
                "timestamp", System.currentTimeMillis());

        return ResponseEntity.ok(result);
    }

    /**
     * 获取AI服务使用统计
     *
     * @param userId 用户ID
     * @return 使用统计
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取AI服务使用统计", description = "获取用户的AI服务使用统计")
    public ResponseEntity<Map<String, Object>> getAiServiceUsageStatistics(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("获取AI服务使用统计: userId={}", userId);

        Map<String, Object> statistics = aiService.getAiServiceUsageStatistics(userId);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 批量处理图片标签识别
     *
     * @param files  图片文件列表
     * @param userId 用户ID
     * @return 批量识别结果
     */
    @PostMapping("/image/batch-tag-recognition")
    @Operation(summary = "批量图片标签识别", description = "批量识别多张图片的标签")
    public ResponseEntity<Map<String, List<String>>> batchRecognizeImageTags(
            @Parameter(description = "图片文件列表") @RequestParam("files") List<MultipartFile> files,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("批量图片标签识别: userId={}, fileCount={}", userId, files.size());

        Map<String, List<String>> results = aiService.batchRecognizeImageTags(files, userId);
        return ResponseEntity.ok(results);
    }

    /**
     * 批量生成文案
     *
     * @param request 批量生成请求
     * @param userId  用户ID
     * @return 批量生成结果
     */
    @PostMapping("/copywriting/batch-generate")
    @Operation(summary = "批量生成文案", description = "批量生成多个文案")
    public ResponseEntity<List<String>> batchGenerateCopywriting(
            @Valid @RequestBody Map<String, Object> request,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("批量生成文案: userId={}", userId);

        @SuppressWarnings("unchecked")
        List<String> prompts = (List<String>) request.get("prompts");
        String contentType = (String) request.get("contentType");
        String style = (String) request.get("style");
        String aiModel = (String) request.get("aiModel");

        List<String> copywritings = aiService.batchGenerateCopywriting(prompts, contentType, style, aiModel, userId);
        return ResponseEntity.ok(copywritings);
    }

    /**
     * 获取支持的AI服务类型
     *
     * @return 支持的服务类型列表
     */
    @GetMapping("/service-types")
    @Operation(summary = "获取支持的AI服务类型", description = "获取所有支持的AI服务类型")
    public ResponseEntity<List<String>> getSupportedAiServiceTypes() {
        log.info("获取支持的AI服务类型");

        List<String> serviceTypes = aiService.getSupportedAiServiceTypes();
        return ResponseEntity.ok(serviceTypes);
    }

    /**
     * 获取支持的AI提供商
     *
     * @return 支持的提供商列表
     */
    @GetMapping("/providers")
    @Operation(summary = "获取支持的AI提供商", description = "获取所有支持的AI服务提供商")
    public ResponseEntity<List<String>> getSupportedAiProviders() {
        log.info("获取支持的AI提供商");

        List<String> providers = aiService.getSupportedAiProviders();
        return ResponseEntity.ok(providers);
    }

    /**
     * 获取支持的AI模型
     *
     * @param provider    提供商
     * @param serviceType 服务类型
     * @return 支持的模型列表
     */
    @GetMapping("/models")
    @Operation(summary = "获取支持的AI模型", description = "获取指定提供商和服务类型的AI模型")
    public ResponseEntity<List<String>> getSupportedAiModels(
            @Parameter(description = "提供商") @RequestParam(required = false) String provider,
            @Parameter(description = "服务类型") @RequestParam(required = false) String serviceType) {
        log.info("获取支持的AI模型: provider={}, serviceType={}", provider, serviceType);

        List<String> models = aiService.getSupportedAiModels(provider, serviceType);
        return ResponseEntity.ok(models);
    }

    /**
     * 测试AI配置连接
     *
     * @param configId 配置ID
     * @return 测试结果
     */
    @PostMapping("/config/{configId}/test")
    @Operation(summary = "测试AI配置连接", description = "测试AI配置的连接状态")
    public ResponseEntity<Map<String, Object>> testAiConfigConnection(
            @Parameter(description = "配置ID") @PathVariable Long configId,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("测试AI配置连接: configId={}, userId={}", configId, userId);

        boolean success = aiService.testAiConfigConnection(configId);

        Map<String, Object> result = Map.of(
                "configId", configId,
                "success", success,
                "message", success ? "连接成功" : "连接失败",
                "timestamp", System.currentTimeMillis());

        return ResponseEntity.ok(result);
    }

    /**
     * 获取AI服务价格信息
     *
     * @param serviceType 服务类型
     * @param provider    提供商
     * @return 价格信息
     */
    @GetMapping("/pricing")
    @Operation(summary = "获取AI服务价格信息", description = "获取AI服务的价格信息")
    public ResponseEntity<Map<String, Object>> getAiServicePricing(
            @Parameter(description = "服务类型") @RequestParam(required = false) String serviceType,
            @Parameter(description = "提供商") @RequestParam(required = false) String provider) {
        log.info("获取AI服务价格信息: serviceType={}, provider={}", serviceType, provider);

        Map<String, Object> pricing = aiService.getAiServicePricing(serviceType, provider);
        return ResponseEntity.ok(pricing);
    }

    /**
     * 计算AI服务消耗成本
     *
     * @param request 计算请求
     * @return 成本信息
     */
    @PostMapping("/cost/calculate")
    @Operation(summary = "计算AI服务消耗成本", description = "计算AI服务的消耗成本")
    public ResponseEntity<Map<String, Object>> calculateAiServiceCost(
            @Valid @RequestBody Map<String, Object> request) {
        log.info("计算AI服务消耗成本");

        String serviceType = (String) request.get("serviceType");
        String provider = (String) request.get("provider");
        String model = (String) request.get("model");
        Integer usage = (Integer) request.get("usage");

        BigDecimal cost = aiService.calculateAiServiceCost(serviceType, provider, model, usage);

        Map<String, Object> result = Map.of(
                "serviceType", serviceType,
                "provider", provider,
                "model", model,
                "usage", usage,
                "cost", cost,
                "currency", "CNY");

        return ResponseEntity.ok(result);
    }

    /**
     * 获取用户AI配额使用情况
     *
     * @param userId 用户ID
     * @return 配额使用情况
     */
    @GetMapping("/quota/usage")
    @Operation(summary = "获取用户AI配额使用情况", description = "获取用户的AI服务配额使用情况")
    public ResponseEntity<Map<String, Object>> getUserAiQuotaUsage(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("获取用户AI配额使用情况: userId={}", userId);

        Map<String, Object> quotaUsage = aiService.getUserAiQuotaUsage(userId);
        return ResponseEntity.ok(quotaUsage);
    }

    /**
     * 重置用户每日配额
     *
     * @param userId 用户ID
     * @return 重置结果
     */
    @PostMapping("/quota/reset-daily")
    @Operation(summary = "重置用户每日配额", description = "重置用户的每日AI服务配额")
    public ResponseEntity<Map<String, Object>> resetUserDailyQuota(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("重置用户每日配额: userId={}", userId);

        aiService.resetUserDailyQuota(userId);

        Map<String, Object> result = Map.of(
                "userId", userId,
                "message", "每日配额已重置",
                "timestamp", System.currentTimeMillis());

        return ResponseEntity.ok(result);
    }
}